package control

import (
	"context"
	"fmt"
	"fresh-food/api/request"
	"fresh-food/inits/initialize"
	"fresh-food/models"
	"fresh-food/pkg"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"time"
)

func UserSms(c *gin.Context) {
	var data request.SendSms
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	code := rand.Intn(9000) + 1000

	//sms, err := pkg.SendSms(data.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return
	//}
	//if *sms.Body.Code != "OK" {
	//	c.JSON(http.StatusOK, gin.H{
	//		"code": 0,
	//		"msg":  *sms.Body.Message,
	//		"data": nil,
	//	})
	//	return
	//}

	initialize.Client.Set(context.Background(), "SendSms:"+data.Source+data.Mobile, code, time.Minute*2)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "短信验证码发送成功",
		"data": true,
	})

}

func UserLogin(c *gin.Context) {
	var data request.Login
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	if len(data.Mobile) != 11 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "手机号格式不正确",
			"data": nil,
		})
		return
	}

	get := initialize.Client.Get(context.Background(), "SendSms:login"+data.Mobile)

	if get.Val() != data.Sms {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证码错误,请重试",
			"data": nil,
		})
		return
	}

	u := models.User{}

	users, err := u.FindUserByMobile(data.Mobile)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "该用户还未注册",
			"data": nil,
		})
		return
	}
	fmt.Println(users.ID)

	id := pkg.CustomClaims{
		ID: users.ID,
	}
	token, err := pkg.NewJWT("2209a").CreateToken(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "token生成错误",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户登陆成功",
		"data": token,
	})
	return

}

func OrderList(c *gin.Context) {

	userId := c.GetUint("userId")
	o := models.Order{}
	order, err := o.FindOrder(userId)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "列表展示错误",
			"data": nil,
		})
		return
	}

	var orders []*models.Order
	for _, i := range order {
		orders = append(orders, &models.Order{
			UserId:    i.UserId,
			ProductId: i.ProductId,
			OrderSn:   i.OrderSn,
			Num:       i.Num,
			Total:     i.Total,
			Status:    i.Status,
			Pay:       i.Pay,
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": order,
	})
}
